﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using OpGen.Extensions.Security;
using OpGen.Extensions.Network;

namespace OpGen.Extensions.Runtime.Server
{
    internal class ServerMessageTargetContainer<TMessage, TClient> : MethodTargetAuthentication, IServerMessageTargetContainer<TClient> 
    {
        private ServerMessageTargetDelegate<TMessage, TClient> _target;
        private int _opCode;

        public ServerMessageTargetContainer(ServerMessageTargetDelegate<TMessage, TClient> target, int opCode)
        {
            _target = target;
            _opCode = opCode;
            base.Authentication = MethodAuthenticationTypes.Always;
        }

        public ServerMessageTargetContainer(ServerMessageTargetDelegate<TMessage, TClient> target, int opCode, MethodAuthenticationTypes authentication)
        {
            _target = target;
            _opCode = opCode;
            base.Authentication = authentication;
        }

        public int OpCode
        {
            get { return _opCode; }
        }

        public ServerMessageTargetDelegate<TMessage, TClient> Target
        {
            get { return _target; }
        }

        public void Invoke(TClient client, byte[] data)
        {
            if (base.GetAuthenticationStatus((IConnection)client) == AuthenticationStatus.Anonymous & base.Authentication == MethodAuthenticationTypes.RequestAuthentication)
                throw new OpGenException("Invlaide Authentication Status");

            var message = (TMessage)Activator.CreateInstance(typeof(TMessage), new object[] { data });
            _target.Invoke(client, message);
        }
    }
}
